<template>
  <div class="auth-container">
    <div class="auth-card">
      <!-- 标题区域 -->
      <div class="auth-header">
        <h1 class="auth-title">CRM管理系统</h1>
        <p class="auth-subtitle">{{ isLogin ? '欢迎回来' : '创建新账户' }}</p>
      </div>

      <!-- 切换按钮 -->
      <div class="auth-tabs">
        <el-button 
          :type="isLogin ? 'primary' : 'default'"
          @click="switchMode('login')"
          class="tab-button"
        >
          登录
        </el-button>
        <el-button 
          :type="!isLogin ? 'primary' : 'default'"
          @click="switchMode('register')"
          class="tab-button"
        >
          注册
        </el-button>
      </div>

      <!-- 登录表单 -->
      <el-form 
        v-if="isLogin"
        :model="loginForm" 
        :rules="loginRules"
        ref="loginFormRef"
        @submit.prevent="handleLogin" 
        class="auth-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit" 
            :loading="loading"
            size="large"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 注册表单 -->
      <el-form 
        v-else
        :model="registerForm" 
        :rules="registerRules"
        ref="registerFormRef"
        @submit.prevent="handleRegister" 
        class="auth-form"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="User"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="请输入邮箱" 
            prefix-icon="Message"
            size="large"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请确认密码" 
            prefix-icon="Lock"
            show-password
            size="large"
          />
        </el-form-item>
        <el-form-item prop="realName">
          <el-input 
            v-model="registerForm.realName" 
            placeholder="请输入真实姓名" 
            prefix-icon="UserFilled"
            size="large"
          />
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit" 
            :loading="loading"
            size="large"
            style="width: 100%"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 底部提示 -->
      <div class="auth-footer">
        <p v-if="isLogin">
          还没有账户？ 
          <el-link type="primary" @click="switchMode('register')">立即注册</el-link>
        </p>
        <p v-else>
          已有账户？ 
          <el-link type="primary" @click="switchMode('login')">立即登录</el-link>
        </p>
      </div>

      <!-- 开发模式切换 -->
      <div class="dev-mode">
        <el-switch
          v-model="enableRealAPI"
          active-text="真实API"
          inactive-text="模拟模式"
          size="small"
        />
        <span class="dev-mode-tip">开发模式切换</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, register } from '@/api/auth'

const isLogin = ref(true)
const loading = ref(false)
const authStore = useAuthStore()
const router = useRouter()

// 配置选项：是否启用真实API调用
const enableRealAPI = ref(true) // 默认开启真实API

// 表单引用
const loginFormRef = ref()
const registerFormRef = ref()

// 登录表单
const loginForm = reactive({
  username: '',
  password: ''
})

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  realName: ''
})

// 登录验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 注册验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ]
}

// 切换登录/注册模式
const switchMode = (mode) => {
  isLogin.value = mode === 'login'
  // 清空表单
  if (mode === 'login') {
    Object.keys(loginForm).forEach(key => {
      loginForm[key] = ''
    })
  } else {
    Object.keys(registerForm).forEach(key => {
      registerForm[key] = ''
    })
  }
}

// 处理登录
const handleLogin = async () => {
  console.log('handleLogin called', loginForm)
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    if (enableRealAPI.value) {
      // 只调用 store 的 login 方法
      await authStore.login(loginForm)
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      await handleMockLogin()
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('登录失败，请检查用户名和密码')
    }
  } finally {
    loading.value = false
  }
}

// 模拟登录处理
const handleMockLogin = async () => {
  console.log('使用模拟登录模式')
  const mockUser = {
    token: 'mock-token-' + Date.now(),
    user: {
      id: 1,
      username: loginForm.username,
      name: loginForm.username,
      role: 'user',
      avatar: ''
    }
  }
  
  await authStore.login(mockUser)
  ElMessage.success('登录成功（模拟模式）')
  router.push('/')
}

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    if (enableRealAPI.value) {
      // 启用真实API调用
      try {
        const registerData = {
          username: registerForm.username,
          email: registerForm.email,
          password: registerForm.password,
          realName: registerForm.realName
        }
        await register(registerData)
        ElMessage.success('注册成功，请登录')
        router.push('/register-success')
      } catch (apiError) {
        console.warn('API调用失败，切换到模拟模式:', apiError)
        // API调用失败时自动切换到模拟模式
        await handleMockRegister()
      }
    } else {
      // 使用模拟注册
      await handleMockRegister()
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('注册失败，请重试')
    }
  } finally {
    loading.value = false
  }
}

// 模拟注册处理
const handleMockRegister = async () => {
  console.log('使用模拟注册模式')
  await new Promise(resolve => setTimeout(resolve, 1000))
  ElMessage.success('注册成功（模拟模式），请登录')
  router.push('/register-success')
}
</script>

<style scoped>
.auth-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.auth-card {
  width: 100%;
  max-width: 450px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.auth-header {
  text-align: center;
  padding: 40px 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.auth-title {
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.auth-subtitle {
  font-size: 16px;
  margin: 0;
  opacity: 0.9;
}

.auth-tabs {
  display: flex;
  padding: 0 40px;
  background: #f8f9fa;
}

.tab-button {
  flex: 1;
  border-radius: 0;
  border: none;
  padding: 15px;
  font-size: 16px;
  font-weight: 500;
}

.tab-button:first-child {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.tab-button:last-child {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.auth-form {
  padding: 30px 40px;
}

.auth-footer {
  text-align: center;
  padding: 20px 40px 30px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.auth-footer p {
  margin: 0;
  color: #6c757d;
}

.dev-mode {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  background: rgba(255, 255, 255, 0.9);
  padding: 8px 12px;
  border-radius: 20px;
  -webkit-backdrop-filter: blur(10px); /* 兼容 Safari */
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.dev-mode-tip {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-card {
    margin: 10px;
  }
  
  .auth-header,
  .auth-form,
  .auth-footer {
    padding-left: 20px;
    padding-right: 20px;
  }
  
  .auth-tabs {
    padding: 0 20px;
  }
  
  .dev-mode {
    position: static;
    margin: 10px 20px;
    justify-content: center;
  }
}
</style>